<template>
  <div class="edit-travel-plan">
    <h1 class="page-title">编辑旅游计划</h1>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>
    
    <el-form v-else :model="travelPlanForm" :rules="rules" ref="travelPlanFormRef" label-width="100px" class="travel-plan-form">
      <el-form-item label="计划标题" prop="title">
        <el-input v-model="travelPlanForm.title" placeholder="请输入旅行计划标题" maxlength="50" show-word-limit></el-input>
      </el-form-item>
      
      <el-form-item label="计划描述" prop="description">
        <el-input v-model="travelPlanForm.description" type="textarea" :rows="4" placeholder="请输入旅行计划描述" maxlength="500" show-word-limit></el-input>
      </el-form-item>
      
      <el-form-item label="封面图片" prop="coverImage">
        <el-upload
          class="cover-uploader"
          action="#"
          :http-request="uploadCoverImage"
          :show-file-list="false"
          :before-upload="beforeCoverUpload"
          v-loading="coverUploading"
          :element-loading-text="`上传中... ${coverUploadPercent}%`"
          element-loading-background="rgba(255,255,255,0.8)">
          <img
            v-if="coverPreview || travelPlanForm.coverImage"
            :src="coverPreview || travelPlanForm.coverImage"
            class="cover-image"
            @error="handleCoverError"
          />
          <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="form-tip">
          <span>建议上传尺寸比例为16:9的图片，大小不超过2MB</span>
        </div>
      </el-form-item>
      
      <el-form-item label="主要城市" prop="cityId">
        <el-select v-model="travelPlanForm.cityId" placeholder="请选择主要城市" filterable class="full-width-select">
          <el-option
            v-for="city in cityOptions"
            :key="city.id"
            :label="city.name"
            :value="city.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="出行日期" prop="startDate">
        <el-date-picker
          v-model="travelPlanForm.startDate"
          type="date"
          placeholder="选择出行日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
          class="full-width-date">
        </el-date-picker>
      </el-form-item>
      

      <el-form-item label="是否公开" prop="isPublic">
        <el-switch
          v-model="travelPlanForm.isPublic"
          active-text="公开"
          inactive-text="私密"
          class="status-switch">
        </el-switch>
        <div class="form-tip" v-if="travelPlanForm.isPublic">
          <el-alert
            title="公开的旅行计划将发送给管理员审核，审核通过后将发布到旅游圈论坛"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </div>
      </el-form-item>
      

      
      <el-form-item class="form-actions">
        <el-button type="primary" @click="submitForm" :loading="submitting" size="large">
          <el-icon><Check /></el-icon>保存修改
        </el-button>
        <el-button @click="resetForm" size="large">
          <el-icon><RefreshRight /></el-icon>重置
        </el-button>
        <el-button @click="goBack" size="large">
          <el-icon><Back /></el-icon>返回
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, RefreshRight, Back, Plus } from '@element-plus/icons-vue'
import { getCities } from '../../api/city'
import { uploadImage } from '../../api/upload'
import { getTravelPlanById, updateTravelPlan } from '../../api/travelPlan'

const router = useRouter()
const route = useRoute()
const travelPlanFormRef = ref(null)
const loading = ref(true)
const submitting = ref(false)
// 本地预览与上传状态
const coverPreview = ref('')
const coverUploading = ref(false)
const coverUploadPercent = ref(0)

// 获取路由参数中的计划ID
const planId = route.params.id

// 表单数据
const travelPlanForm = reactive({
  title: '',
  description: '',
  cityId: '',
  startDate: '',
  isPublic: false,
  status: 'draft', // 默认为草稿状态
  days: 1, // 默认出行天数为1天
  coverImage: '' // 封面图片
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入计划标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入计划描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  cityId: [
    { required: true, message: '请选择主要城市', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择出行日期', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value) {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          const selectedDate = new Date(value)
          if (selectedDate < today) {
            callback(new Error('出行日期不能早于今天'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 禁用今天之前的日期
const disabledDate = (time) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return time.getTime() < today.getTime()
}

// 城市选项，实际应从API获取
const cityOptions = ref([])

// 获取城市列表
const fetchCities = async () => {
  try {
    const cities = await getCities()
    cityOptions.value = cities.map(c => ({ id: c.id, name: c.name }))
  } catch (error) {
    console.error('获取城市列表失败:', error)
    ElMessage.error('获取城市列表失败')
  }
}

// 图片上传前的验证
const beforeCoverUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('封面图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('封面图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理图片上传：先显示本地预览，再上传并替换为云端URL
const uploadCoverImage = async (options) => {
  const { file, onSuccess, onError, onProgress } = options

  // 本地预览
  try {
    if (coverPreview.value && coverPreview.value.startsWith('blob:')) {
      URL.revokeObjectURL(coverPreview.value)
    }
    coverPreview.value = URL.createObjectURL(file)
  } catch {}

  coverUploading.value = true
  coverUploadPercent.value = 0

  try {
    const result = await uploadImage(file, (percent) => {
      coverUploadPercent.value = percent
      if (onProgress) onProgress({ percent })
    })

    if (result?.success && result.data?.url) {
      travelPlanForm.coverImage = result.data.url
      coverPreview.value = travelPlanForm.coverImage
      ElMessage.success('封面图片上传成功')
      if (onSuccess) onSuccess(result.data)
    } else {
      throw new Error(result?.message || '上传失败')
    }
  } catch (err) {
    console.error('封面上传失败:', err)
    ElMessage.error(err.message || '封面上传失败')
    if (onError) onError(err)
  } finally {
    coverUploading.value = false
  }
}

// 图片加载错误时回退到占位
const handleCoverError = () => {
  if (!coverPreview.value) {
    travelPlanForm.coverImage = ''
  }
}

// 获取旅行计划详情
const fetchTravelPlan = async () => {
  loading.value = true
  try {
    const data = await getTravelPlanById(planId)
    if (!data) throw new Error('未找到旅行计划')
    Object.assign(travelPlanForm, {
      title: data.title || '',
      description: data.description || '',
      cityId: data.cityId || '',
      startDate: data.startDate || '',
      isPublic: !!data.isPublic,
      status: data.status || 'draft',
      days: data.days || 1,
      coverImage: data.coverImage || ''
    })
  } catch (error) {
    console.error('获取旅行计划详情失败:', error)
    ElMessage.error('获取旅行计划详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!travelPlanFormRef.value) return
  await travelPlanFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 设置审核状态逻辑
        // 如果是公开的，则设置为审核中状态
        // 如果是私密的，则保持草稿状态
        const status = travelPlanForm.isPublic ? 'pending' : 'draft'
        
        const payload = {
          title: travelPlanForm.title,
          description: travelPlanForm.description,
          cityId: travelPlanForm.cityId,
          startDate: travelPlanForm.startDate,
          isPublic: travelPlanForm.isPublic,
          status: status, // 添加状态字段
          days: travelPlanForm.days, // 添加出行天数字段
          coverImage: travelPlanForm.coverImage // 添加封面图片
        }
        await updateTravelPlan(planId, payload)
        ElMessage({ type: 'success', message: '旅行计划更新成功', duration: 2000 })
        if (travelPlanForm.isPublic) {
          ElMessage({ type: 'info', message: '您的旅行计划已提交审核，审核通过后将发布到旅游圈论坛', duration: 3000 })
        }
        router.push(`/travel-plan/${planId}`)
      } catch (error) {
        console.error('更新旅行计划失败:', error)
        ElMessage.error('更新旅行计划失败')
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.warning('请正确填写表单内容')
      return false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchCities()
  fetchTravelPlan()
})
</script>

<style scoped>
.edit-travel-plan {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-title {
  margin-bottom: 30px;
  text-align: center;
  color: #409EFF;
  font-size: 28px;
  font-weight: 600;
}

.travel-plan-form {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

/* 封面图片上传样式 */
.cover-uploader {
  width: 360px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.cover-uploader-icon {
  font-size: 40px;
  color: #8c939d;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loading-container {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.form-tip-text {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.full-width-select {
  width: 100%;
}

.full-width-date {
  width: 100%;
}

.status-switch {
  margin-right: 10px;
}

/* 每日计划样式 */

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-button) {
  margin-right: 15px;
}

:deep(.el-button .el-icon) {
  margin-right: 5px;
}

@media (max-width: 768px) {
  .edit-travel-plan {
    padding: 10px;
  }
  
  .travel-plan-form {
    padding: 20px;
  }
  
  :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 10px;
  }
  
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>